package com.platform.common.utils.pay;

import com.platform.common.config.WxPayConfig;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.HttpHost;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

public class CertificatesManager {
    private CloseableHttpClient httpClient;
    com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager certificatesManager;
    Verifier verifier;

    private static final HttpHost proxy = null;

    public void setup() throws Exception {
        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(WxPayConfig.privateKeyForDecrypt);
        // 获取证书管理器实例
        certificatesManager = com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager.getInstance();
        // 添加代理服务器
        certificatesManager.setProxy(proxy);
        // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(WxPayConfig.mchid, new WechatPay2Credentials(WxPayConfig.mchid,
                        new PrivateKeySigner(WxPayConfig.mchSerialNo, merchantPrivateKey)),
                WxPayConfig.apiV3Key.getBytes(StandardCharsets.UTF_8));
        // 从证书管理器中获取verifier
        verifier = certificatesManager.getVerifier(WxPayConfig.mchid);
        // 构造httpclient
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(WxPayConfig.mchid, WxPayConfig.mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

    public void after() throws IOException {
        httpClient.close();
    }
}
